<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body {

            padding: 0;
            margin: 0;
            background: black;
        }

        #zone {
            width: 300px;
            height: 300px;
            margin: 100px auto 0;
            background: lightyellow;
            border: solid 1px skyblue;
            line-height: 300px;
            text-align: center;
        }

        #imgList {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            width: 1200px;
            margin: 20px auto;
        }

        #imgList li {
            display: flex;
            margin: 10px;
        }

        img {
            width: 150px;
            height: 200px;
        }

        #btn {
            width: 200px;
            height: 80px;
            margin: 0 auto;
            background: #ddd;
            border: solid 1px yellow;
            border-radius: 10px;
        }
    </style>
</head>

<body>
    <div id="zone">将片拖拽到此处</div>
    <div class="btn"><button id="btn">点击上传</button></div>
    <ul id="imgList"></ul>
    <script>
        //获取窗口宽高
        let W = document.documentElement.clientWidth;
        let H = document.documentElement.clientHeight;
        console.log('W:' + W + ',' + 'H:' + H);
        //窗口 设置宽高
        document.body.style.width = W;
        document.body.style.height = H;

        const zone = document.getElementById('zone')
        let imgList = document.getElementById('imgList')
        //dragover 禁止默认事件
        zone.addEventListener("dragover", (e) => {
            e.preventDefault();
            e.stopPropagation();
            return false;
        })
        //drop
        zone.addEventListener("drop", (e) => {
            // 文件挂载
            let file = e.dataTransfer.files.item(0);
            console.log(file);

            //读取文件
            let f = new FileReader();
            f.readAsDataURL(file)


            // 显示文件
            f.onload = () => {
                let img = new Image();
                img.src = f.result

                let El = imgList.appendChild(img)
            }

            //ajax 上传  使用fetch
            let btn = document.getElementById('btn')
            btn.onclick = () => {
                //fetch(路径，请求数据)
                let form = new FormData()
                // form.append('文件名',文件数据)
                form.append('file', e.dataTransfer.files.item(i))
                fetch('http://localhost:334/upload', {
                        method: 'get',
                        body: form
                    })
                    .then(console.log('上传成功'))
            }

            e.preventDefault();
            e.stopPropagation();
            return false;
        })
    </script>
</body>

</html>